<template>
	<view style="width: 100%;">
		<uni-card v-for="(item, index) in data" :key="item.secretKey" :title="item.name" thumbnail="" extra=""
			note="Tips" @click="delItem(index)">
			<text style="font-size: 32px;color: #2979ff;font-weight: bold;">{{item.code}}</text>
		</uni-card>
		<!-- 悬浮按钮 -->
		<uni-fab :pattern='toolPattern' horizontal='right' vertical='bottom' direction='horizontal'
			:content='toolContent' @trigger="fabClick" />
		<!-- 新增 -->
		<uni-popup ref="popup" background-color="#fff">
			<view
				style="width: 100%;display: flex; flex-direction: column;justify-content: center;align-items: center;">
				<view style="width: 90%;margin: 100rpx 0 50rpx 0;">
					<uni-easyinput placeholder="请输入名称" v-model="form.name" />
				</view>
				<view style="width: 90%;margin: 25rpx 0 50rpx 0;">
					<uni-easyinput placeholder="请输入秘钥" v-model="form.secretKey" />
				</view>
				<view style="width: 90%;margin: 25rpx 0 50rpx 0; margin-bottom: 50rpx;">
					<button @click="addItem" type="primary" style="line-height: 2;">添加</button>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="delDialog" type="dialog">
			<uni-popup-dialog type="warning" cancelText="取消" confirmText="删除" title="警告" :content="delTitle" @confirm="deleteItem(delIndex)" />
		</uni-popup>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 请求地址
				baseUrl: 'http://ip:port/google-auth/',
				// 是否请求标志
				flag: -1,
				// 数据
				data: [],
				// 删除参数
				delIndex: -1,
				delTitle: '',
				// 添加参数
				form: {
					name: '',
					secretKey: ''
				},
				toolPattern: {
					buttonColor: '#2979ff'
				},
				toolContent: [{
						iconPath: '/static/input.png',
						text: '手动输入'
					},
					{
						iconPath: '/static/scan.png',
						text: '扫码输入'
					}
				]
			}
		},
		onLoad() {
			// 获取值
			let data = uni.getStorageSync('data');
			if (0 < data.length) {
				for (let i = 0, len = data.length;i < len; i++) {
					data[i].code = ''
				}
				this.data = data
			}
			this.init();
			// 循环获取code
			setInterval(() => {
				this.init();
			}, 1000);
		},
		methods: {
			init() {
				// 第一次进入
				if (-1 === this.flag) {
					// 当前秒数
					let second = this.getSecond();
					if (0 <= second && second <= 30) {
						this.flag = 1;
					} else {
						this.flag = 2;
					}
					// 刷新code
					this.refreshCode();
					return;
				}
				// 当前秒数
				let second = this.getSecond();
				let flag = -1;
				if (0 < second && second <= 30) {
					flag = 1;
				} else {
					flag = 2;
				}
				if (this.flag !== flag) {
					this.flag = flag
					// 刷新code
					this.refreshCode();
				}
			},
			// 获取当前秒数
			getSecond() {
				let date = new Date();
				return date.getSeconds();
			},
			// 刷新code
			refreshCode() {
				if (0 === this.data.length) {
					return
				}
				for (let i = 0, len = this.data.length; i < len; i++) {
					this.getCode(i, this.data[i].secretKey);
				}
			},
			// 获取code
			getCode(index, secretKey) {
				uni.request({
					url: this.baseUrl + 'getCode?secretKey=' + secretKey,
					method: 'GET',
					success: (res) => {
						let code = res.data + '';
						this.data[index].code = code.substr(0, 3) + ' ' + code.substr(3, 3)
					}
				})
			},
			// 添加
			addItem() {
				if (!this.form.name) {
					uni.showToast({
						title: '请输入名称',
						icon: 'error'
					})
					return
				}
				if (!this.form.secretKey) {
					uni.showToast({
						title: '请输入秘钥',
						icon: 'error'
					})
					return
				}
				if (32 > this.form.secretKey.length) {
					uni.showToast({
						title: '秘钥格式不正确',
						icon: 'error'
					})
					return
				}
				if (this.isExist(this.form.secretKey)) {
					uni.showToast({
						title: '密钥已存在',
						icon: 'error'
					})
					return
				}
				this.data.push({
					name: this.form.name,
					secretKey: this.form.secretKey,
					code: ''
				})
				this.getCode(this.data.length - 1, this.form.secretKey)
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				})
				this.form = {
					name: '',
					secretKey: ''
				}
				uni.setStorageSync('data', this.data)
				this.$refs.popup.close()
			},
			// 删除
			delItem(index) {
				this.delIndex = index
				this.delTitle = '确认删除 ' + this.data[index].name + ' ?'
				this.$refs.delDialog.open()
			},
			deleteItem() {
				this.data.splice(this.delIndex, 1);
				// 删除缓存
				uni.setStorageSync('data', this.data);
				uni.showToast({
					title: '删除成功',
					icon: 'error'
				})
			},
			// 密钥是否存在
			isExist(secretKey) {
				if (0 === this.data.length) {
					return false;
				}
				for (let i = 0, len = this.data.length; i < len; i++) {
					if (secretKey === this.data[i].secretKey) {
						return true;
					}
				}
				return false
			},
			// 手动添加
			openAdd() {
				this.$refs.popup.open('bottom')
			},
			// 扫码添加
			scanAdd() {
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let url = res.result;
						if (!url.startsWith('otpauth://totp/')) {
							uni.showToast({
								title: '未识别到有效信息',
								icon: 'error'
							})
							return
						}
						let temp = url.replace('otpauth://totp/', '');
						let arr = temp.split('?');
						let name = decodeURIComponent(arr[0]) || '未知';
						let secretKey = this.getParam('secret', url);
						if (!secretKey) {
							uni.showToast({
								title: '缺少密钥信息',
								icon: 'error'
							})
							return
						}
						if (32 > secretKey.length) {
							uni.showToast({
								title: '秘钥格式不正确',
								icon: 'error'
							})
							return
						}
						if (this.isExist(secretKey)) {
							uni.showToast({
								title: '密钥已存在',
								icon: 'error'
							})
							return
						}
						this.data.push({
							name: name,
							secretKey: secretKey,
							code: ''
						});
						this.getCode(this.data.length - 1, secretKey)
						uni.showToast({
							title: '添加成功',
							icon: 'success'
						})
						uni.setStorageSync('data', this.data)
					},
					fail: (res) => {

					}
				})
			},
			// 下拉刷新
			onPullDownRefresh() {
				this.init();
				setTimeout(() => {
					uni.stopPullDownRefresh();
				}, 500)
			},
			// 从url中获取参数
			getParam(key, url) {
				let query = url.split('?')[1];
				var vars = query.split("&");
				for (var i = 0; i < vars.length; i++) {
					var pair = vars[i].split("=");
					if (pair[0] == key) {
						return pair[1];
					}
				}
				return (false);
			},
			// 按钮点击
			fabClick(e) {
				if (0 == e.index) {
					this.openAdd();
				} else {
					this.scanAdd();
				}
			}
		}
	}
</script>

<style>
	page {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
	}
</style>
